<?php

namespace App\Templates;


use App\Events\RegSuccess;
use App\Models\MLog;
use App\Models\MUser;
use App\Utils\TreeUtil;
use DB;
use Exception;
use Illuminate\Http\Request;

/**
 * 注册会员的请求处理
 */
trait RegUserAct
{
    public function regUserSave(Request $request)
    {
        if (!$this->validateReq($request, MUser::regRulesWithMsg(0), MUser::regRulesWithMsg(1))) {
            $this->data = $this->makeJsCode(1, $this->errors->first());
            return response()->json($this->data);
        }
        $user = new MUser();

        //检查会员是否重名
        if ($user->existUserName($request->username)) {
            $this->data = $this->makeJsCode(1, "用户名已经存在！");
            return response()->json($this->data);
        }

        //检查报单中心
        $bdzx = TreeUtil::checkBdzxByName($request->bdzx);
        if (empty($bdzx)) {
            $this->data = $this->makeJsCode(1, "无效的报单中心！");
            return response()->json($this->data);
        }

        //检查推荐人
        $puser = TreeUtil::checkPUserByName($request->puser);
        if (empty($puser)) {
            $this->data = $this->makeJsCode(1, "无效的推荐人！");
            return response()->json($this->data);
        }

        //检查节点人
        $addr = MUser::$ADDR_NO;
        $nuser = TreeUtil::checkNUserByName($request->nuser);
        if (empty($nuser)) {
            $this->data = $this->makeJsCode(1, "无效的节点人！");
            return response()->json($this->data);
        } else {//判断节点是否有位置
            $addr = TreeUtil::getNodeAddrByUser($nuser);
            if ($addr == MUser::$ADDR_NO) {
                $this->data = $this->makeJsCode(1, "节点人位置已满！");
                return response()->json($this->data);
            }
        }

        //是否是内部会员注册检查
        if ($request->has('_in_user') && $request->_in_user != env('IN_USER_TOKEN')) {
            $this->data = $this->makeJsCode(1, "内部会员注册失败！");
            return response()->json($this->data);
        }

        try {
            DB::transaction(function () use ($request, $puser, $nuser, $bdzx, $addr, &$user) {
                if ($user->regUser($request, $puser, $nuser, $bdzx, $addr)) {

                    event(new RegSuccess($user));   //发送注册成功事件通知

                    if ($user->in == MUser::$USER_IN) {
                        MLog::log("注册了内部会员 $request->username ( ID: $user->id ) !");
                    }
                    $this->data = $this->makeJsCode(0, "注册成功！");

                } else {
                    DB::rollBack();
                    $this->data = $this->makeJsCode(1, "注册失败！");
                }
            });
        } catch (Exception $e) {
            $this->data = $this->makeJsCode(1, "注册失败！");
        }
        return response()->json($this->data);
    }
}